package dubbo.learn.transport.netty4;


import com.alibaba.fastjson.JSONObject;
import dubbo.learn.common.ResponseVO;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext cx) {
        log.info("channelActive,local address:{},remote address:{}",
                cx.channel().localAddress(),cx.channel().remoteAddress());
    }

    /**
     * 读取信息
     *
     * @param ctx 渠道连接对象
     * @param msg 信息
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ResponseVO responseVO = JSONObject.parseObject((String) msg, ResponseVO.class);
        String requestId = responseVO.getRequestId();

        //获取future
        CompletableFuture<Object> completableFuture = Netty4ClientRpcInvoker.requestId2futureMap
                .get(requestId);
        completableFuture.complete(responseVO.getContent());
        log.info("client channelRead,thread:{}", Thread.currentThread());
        log.info("客户端端读写远程地址是-----------"
                + ctx.channel().remoteAddress() + "信息是：" + msg.toString());

    }

    /**
     * 发生异常关闭连接
     *
     * @param ctx   渠道连接对象
     * @param cause 异常
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
